package mapreduce;

import org.apache.commons.io.output.NullWriter;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class FlowSortMap extends Mapper<LongWritable, Text ,PhoneFlow, NullWritable> {

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        try {

            String data = value.toString();

            String[] strings = data.split("\t");

            PhoneFlow flow = new PhoneFlow();
            Text phone = new Text();

            Long upFlow = new Long(0);
            Long downFlow = new Long(0);

            if (strings.length >= 4) {
                phone.set(new Text(strings[0]));
                try {
                    upFlow = Long.parseLong(strings[1]);
                } catch (Exception e) {
                    upFlow = new Long(0);
                }
                try {
                    downFlow = Long.parseLong(strings[2]);
                } catch (Exception e) {
                    downFlow = new Long(0);
                }

                flow.set(phone.toString(),upFlow, downFlow, upFlow + downFlow);

                context.write(flow, NullWritable.get());
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}